#encoding=utf-8
__author__ = 'Soul'

from core.PageFetcher import *

class IEVPageFetcher(PageFetcher):
    def __init__(self):
         pass

    def __analysis_style1(self, base_div):
        info_list = []
        info_li_list = base_div.xpath("table//tr[1]/tr/td/ul/li")
        for info_li in info_li_list:
            info_list.append(info_li.xpath("div").text())
        return info_list

    def __analysis_style2(self, parsed_html):
        base_div = parsed_html.xpath("//div[@class='right fr']")
        infos_map = {}
        #
        # analysis header
        #
        header_info_map = {}
        header_info_list = base_div.xpath("ul/li")
        for head_info_li in header_info_list:
            key = head_info_li.xpath("//div[@class='l fl']").text()
            value = head_info_li.xpath("//div[@class='l fr']").text()
            header_info_map[key] = value

        infos_map['basic_info'] = header_info_map

        #
        # analysis body
        #
        cont_div = parsed_html.xpath("//div[@class='cont']")
        titles_list = cont_div.xpath("/div")
        tables_list = cont_div.xpath("//table")
        tables_map_list = []
        for i in range(0, len(titles_list)):
            title = titles_list[i].text()

            table = tables_list[i]
            trs_list = table.xpath("//tr")
            trs_map_list = []
            for tr in trs_list:
                key = tr.xpath("td[0]").text()
                value = tr.xpath("td[1]").text()
                trs_map_list.append({key: value})

            tables_map_list.append({title: trs_map_list})
        return tables_map_list

    def analysis(self):
        from lxml.html import fromstring
        parsed_html = fromstring(self.__html_src__)

        base_parent_div = parsed_html.xpath("//div[@class='right fr']")
        content_xml = base_parent_div.xpath("cont1")
        if content_xml:
            self.__analysis_style1(content_xml)
        else:
            self.__analysis_style2(parsed_html)